﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Web;
using EOSCRM.Domain;
using EOSCRM.Util;
using System.Reflection;

namespace EOSCRM.Dao
{
    public class _el_userActionDao
    {
        readonly EventsLogDataContext _db;
        readonly string ConnectionString = "";
        public string SessionIdentify = "_EL_USER";
        private const string _dbName = "EventsLog";
        private const string _dbNameID = "Initial Catalog";
        public string Session4Log = "_INFO_4_LOG";

        public _el_userActionDao()
        {
            var connStr = ConfigurationManager.AppSettings[Constants.SETTINGS_CONNECTION];
            var decryptString = connStr; // EncryptUtil.Decrypt(connStr);

            var arrCS = decryptString.Split(';');
            for (var i = 0; i < arrCS.Length; i++)
            {
                var keyPair = arrCS[i].Split('=');
                if (keyPair.Count() == 2 && keyPair[0] == _dbNameID)
                    // EOSDN_EventsLog
                    arrCS[i] = string.Format("{0}={1}_{2}", keyPair[0], keyPair[1], _dbName);
            }
            ConnectionString = String.Join(";", arrCS);

            _db = new EventsLogDataContext(ConnectionString);
        }

        public el_userAction Get(int IDusrAction) { return _db.el_userActions.SingleOrDefault(w => w.IDusrAct == IDusrAction); }
        public List<el_userAction> GetList() { return _db.el_userActions.OrderBy(o => o.LogID.ToString() + o.logTime.ToString()).ToList(); }

        public void DuplicateType<anyType>(anyType Source, ref anyType Destination)
        {
            var curSession = HttpContext.Current.Session[Session4Log] as string[];
            if (curSession[1] == "") return;
            string[] Fields4Dup = curSession[1].Split(',');
            for (int i = 0; i < Fields4Dup.Length; i++)
                Destination.GetType().GetProperty(Fields4Dup[i]).SetValue(Destination,
                    Source.GetType().GetProperty(Fields4Dup[i]).GetValue(Source, null), null);
        }

        public void Insert<T>(T objToLog, LogType logType)
        {
            var curLog = (HttpContext.Current.Session[SessionIdentify] as EOSCRM.Domain.el_userLog);
            if (curLog==null) return;

            var curSession = HttpContext.Current.Session[Session4Log] as string[];
            if (curSession[1] == "" || int.Parse(curSession[0]) == 0) return;

            int PositionID = int.Parse(curSession[0]);
            string[] Fields4Log = curSession[1].Split(',');

            string newValues = "";
            var objLog = objToLog.GetType();

            for (int i = 0; i < Fields4Log.Length; i++)
            {
                var valField = objLog.GetProperty(Fields4Log[i]).GetValue(objToLog, null);
                if (valField != null) newValues += "[" + Fields4Log[i] + "=" + valField.ToString() + "]";
            }
            if (newValues != "")
            {
                var newRecord = new el_userAction();
                newRecord.LogID = curLog.LogID;
                newRecord.PositionID = PositionID;
                newRecord.logType = logType.GetHashCode();
                newRecord.logTime = DateTime.Now.TimeOfDay;
                newRecord.newValues = newValues;
                _db.el_userActions.InsertOnSubmit(newRecord);
                _db.SubmitChanges();
            }
        }
    }
}
